<template>
  <!--  卡业务-挂失与解挂 -->
  <div class="user-info">
    <div class="all_main">
      <dragdrop :width="0" :widthLeft="'130px'">
        <template slot="left">
          <div class="all_left">
            <div class="grid-content bg-purple">
              <div class="header_title">
                <span>部门列表</span>
              </div>
              <div class="department_tree">
                <el-tree
                  :data="deptTree"
                  :props="defaultProps"
                  @node-click="handleNodeClick"
                  :highlight-current="true"
                  :indent="1"
                  :expand-on-click-node="false"
                   node-key="pkDepartmentId"
                  :default-expanded-keys="idArr"
                ></el-tree>
              </div>
            </div>
          </div>
        </template>
        <template slot="right">
          <div class="all_right">
            <div class="grid-content bg-purple">
              <div class="header_title">
                <span>人员列表</span>
              </div>
              <el-form :inline="true" :model="elform" size="mini" ref="elform" class="form">
                <el-form-item>
                  <el-radio v-model="cardState" :label="-1">全部卡片</el-radio>
                  <el-radio v-model="cardState" :label="0">未挂失卡片</el-radio>
                  <el-radio v-model="cardState" :label="1">挂失卡片</el-radio>
                </el-form-item>
                <el-form-item label="姓名:">
                  <el-input
                    placeholder="用户姓名"
                    v-model="userName"
                    clearable
                    size="mini"
                    style="width: 100px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="编号:">
                  <el-input
                    placeholder="用户编号"
                    v-model="userNumber"
                    clearable
                    size="mini"
                    style="width: 120px"
                  ></el-input>
                </el-form-item>
                <el-form-item label="卡号:">
                  <el-input
                    placeholder="卡号"
                    v-model="cardNumber"
                    clearable
                    size="mini"
                    style="width: 120px"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="gotosearch()" size="mini">查询</el-button>
                  <el-button type="primary" @click="resetfilter()" size="mini">重置条件</el-button>
                  <el-popover placement="top" width="500" trigger="click">
                    <div>
                      <el-row>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.userName.label"
                          v-model="formThead.userName.checked"
                          @change="checkboxChanged()"
                          margin-right:10px
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.userNumber.label"
                          v-model="formThead.userNumber.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.cardNumber.label"
                          v-model="formThead.cardNumber.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.userSexStr.label"
                          v-model="formThead.userSexStr.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                      </el-row>
                      <el-row>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.departmentName.label"
                          v-model="formThead.departmentName.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.groupName.label"
                          v-model="formThead.groupName.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.roomName.label"
                          v-model="formThead.roomName.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.idCard.label"
                          v-model="formThead.idCard.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                      </el-row>
                      <el-row>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.birthday.label"
                          v-model="formThead.birthday.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.phoneNumber.label"
                          v-model="formThead.phoneNumber.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.contact.label"
                          v-model="formThead.contact.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.contactPhone.label"
                          v-model="formThead.contactPhone.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                      </el-row>
                      <el-row>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.homeAddress.label"
                          v-model="formThead.homeAddress.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.postCode.label"
                          v-model="formThead.postCode.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.email.label"
                          v-model="formThead.email.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.regTime.label"
                          v-model="formThead.regTime.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                      </el-row>
                      <el-row>
                        <el-checkbox
                          style="width: 10%"
                          :label="formThead.limitPassword.label"
                          v-model="formThead.limitPassword.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>
                        <!-- <el-checkbox
                          style="width: 10%"
                          :label="formThead.platformBalance.label"
                          v-model="formThead.platformBalance.checked"
                          @change="checkboxChanged()"
                        ></el-checkbox>-->
                      </el-row>
                    </div>
                    <el-button type="primary" slot="reference" size="mini">自定义显示列</el-button>
                  </el-popover>
                </el-form-item>
              </el-form>
              <el-table
                :data="tableData"
                border
                row-key="id"
                :header-cell-style="headFirst"
                ref="tableData"
                :cell-style="(res) => headFirst_col(res, [])"
              >
                <el-table-column
                  :label="formThead.userName.label"
                  :prop="formThead.userName.prop"
                  v-if="formThead.userName.checked"
                ></el-table-column>
                <el-table-column
                  :label="formThead.userNumber.label"
                  :prop="formThead.userNumber.prop"
                  v-if="formThead.userNumber.checked"
                  min-width="110px"
                ></el-table-column>
                <el-table-column
                  :label="formThead.cardNumber.label"
                  :prop="formThead.cardNumber.prop"
                  v-if="formThead.cardNumber.checked"
                  min-width="110px"
                ></el-table-column>
                <el-table-column
                  :label="formThead.departmentName.label"
                  :prop="formThead.departmentName.prop"
                  v-if="formThead.departmentName.checked"
                  min-width="120px"
                ></el-table-column>
                <el-table-column
                  :label="formThead.groupName.label"
                  :prop="formThead.groupName.prop"
                  v-if="formThead.groupName.checked"
                ></el-table-column>
                <el-table-column
                  :label="formThead.roomName.label"
                  :prop="formThead.roomName.prop"
                  v-if="formThead.roomName.checked"
                ></el-table-column>
                <el-table-column
                  :label="formThead.userSexStr.label"
                  :prop="formThead.userSexStr.prop"
                  v-if="formThead.userSexStr.checked"
                ></el-table-column>
                <el-table-column
                  :label="formThead.birthday.label"
                  :prop="formThead.birthday.prop"
                  v-if="formThead.birthday.checked"
                  min-width="94px"
                ></el-table-column>
                <el-table-column
                  :label="formThead.idCard.label"
                  :prop="formThead.idCard.prop"
                  v-if="formThead.idCard.checked"
                ></el-table-column>
                <el-table-column
                  :label="formThead.loginName.label"
                  :prop="formThead.loginName.prop"
                  v-if="formThead.loginName.checked"
                  min-width="110px"
                ></el-table-column>
                <el-table-column
                  :label="formThead.phoneNumber.label"
                  :prop="formThead.phoneNumber.prop"
                  v-if="formThead.phoneNumber.checked"
                  min-width="110px"
                ></el-table-column>
                <el-table-column
                  :label="formThead.contact.label"
                  :prop="formThead.contact.prop"
                  v-if="formThead.contact.checked"
                ></el-table-column>
                <el-table-column
                  :label="formThead.contactPhone.label"
                  :prop="formThead.contactPhone.prop"
                  v-if="formThead.contactPhone.checked"
                ></el-table-column>
                <el-table-column
                  :label="formThead.homeAddress.label"
                  :prop="formThead.homeAddress.prop"
                  v-if="formThead.homeAddress.checked"
                ></el-table-column>
                <el-table-column
                  :label="formThead.postCode.label"
                  :prop="formThead.postCode.prop"
                  v-if="formThead.postCode.checked"
                ></el-table-column>
                <el-table-column
                  :label="formThead.email.label"
                  :prop="formThead.email.prop"
                  v-if="formThead.email.checked"
                ></el-table-column>
                <el-table-column
                  :label="formThead.regTime.label"
                  :prop="formThead.regTime.prop"
                  v-if="formThead.regTime.checked"
                  min-width="154px"
                ></el-table-column>
                <el-table-column
                  :label="formThead.limitPassword.label"
                  :prop="formThead.limitPassword.prop"
                  v-if="formThead.limitPassword.checked"
                ></el-table-column>

                <!-- <el-table-column
                  :label="formThead.platformBalance.label"
                  :prop="formThead.platformBalance.prop"
                  v-if="formThead.platformBalance.checked"
                >
                  <template slot-scope="scope">{{
                    scope.row.platformBalance | amountyuan
                  }}</template>
                </el-table-column>-->
                <el-table-column
                  :label="formThead.advanceBalance.label"
                  :prop="formThead.advanceBalance.prop"
                  v-if="formThead.advanceBalance.checked"
                  min-width="110px"
                >
                  <template slot-scope="scope">
                    {{
                    scope.row.advanceBalance | amountyuan
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" aling="center" v-if="isauth('user_edit')">
                  <template slot-scope="scope">
                    <div v-if="scope.row.cardNumber">
                      <el-button
                        type="text"
                        size="mini"
                        v-if="scope.row.cardState == 0"
                        @click="cardLoss(scope.row, 1)"
                      >挂失</el-button>
                      <el-button
                        type="text"
                        size="mini"
                        style="color: orange"
                        v-if="scope.row.cardState == 1"
                        @click="cardLoss(scope.row, 0)"
                      >解挂</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <div class="page">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChangepage"
                  :current-page="currentPage"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="recordCount"
                ></el-pagination>
              </div>
            </div>
          </div>
        </template>
      </dragdrop>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import { JSEncrypt } from 'jsencrypt'
import qs from 'qs'
import axios from 'axios'
export default {
  data() {
    //自定义验证密码
    let checkpassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else {
        let passwordReg = /^.*(?=.{3,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/
        if (!passwordReg.test(value)) {
          callback(
            new Error('最少6位，包括至少1个大写字母，小写字母，数字，特殊字符')
          )
        } else {
          callback()
        }
      }
    }
    let checkEmail = (rule, value, callback) => {
      if (!value) {
        // 通过callback传递错误信息
        callback()
      } else {
        let emailReg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
        if (!emailReg.test(value)) {
          callback(new Error('请输入正确的邮箱格式！'))
        } else {
          // 没有错误了就直接调用callback
          callback()
        }
      }
    }
    let checkPhone = (rule, value, callback) => {
      if (!value) {
        // 通过callback传递错误信息
        callback()
      } else {
        let emailReg = /^1[3456789]\d{9}$/
        if (!emailReg.test(value)) {
          callback(new Error('请输入正确的手机号码格式！'))
        } else {
          // 没有错误了就直接调用callback
          callback()
        }
      }
    }

    return {
      // 取消上一次请求
      cancel: null,
      changeschoolid: '',
      administrator: '',
      pageSize: 20,
      pageNum: 1,
      currentPage: 1,
      recordCount: 0,
      sortName: '',
      defaultExpandAll: true,
      departmentGuid: '',
      userName: '',
      userNumber: '',
      cardNumber: '',
      limitUpload: 1,
      defaultProps: {
        children: 'children',
        label: 'departmentName'
      },
      elform:{},
      formThead: {
        userName: { label: '姓名', prop: 'userName', checked: true },
        userNumber: { label: '人员编号', prop: 'userNumber', checked: true },
        cardNumber: { label: '卡号', prop: 'cardNumber', checked: true },
        departmentName: {
          label: '部门',
          prop: 'departmentName',
          checked: true
        },
        groupName: { label: '身份/分组', prop: 'groupName', checked: true },
        roomName: { label: '入住房间', prop: 'roomName', checked: false },
        userSexStr: { label: '性别', prop: 'userSexStr', checked: false },
        birthday: { label: '出生日期', prop: 'birthday', checked: false },
        idCard: { label: '身份证号', prop: 'idCard', checked: false },
        phoneNumber: { label: '手机号', prop: 'phoneNumber', checked: true },
        contact: { label: '联系人', prop: 'contact', checked: false },
        contactPhone: {
          label: '联系电话',
          prop: 'contactPhone',
          checked: false
        },
        homeAddress: { label: '家庭地址', prop: 'homeAddress', checked: false },
        postCode: { label: '邮政编码', prop: 'postCode', checked: false },
        email: { label: 'E_mail', prop: 'email', checked: false },
        regTime: { label: '注册时间', prop: 'regTime', checked: false },
        limitPassword: {
          label: '超额密码',
          prop: 'limitPassword',
          checked: false
        },
        // platformBalance: {
        //   label: "平台钱包余额",
        //   prop: "platformBalance",
        //   checked: true,
        // },
        advanceBalance: {
          label: '预存款金额(元)',
          prop: 'advanceBalance',
          checked: true
        },
        loginName: { label: '登陆名', prop: 'loginName', checked: true }
      },
      tableData: [],
      deptTree: [],
      idArr: [null],
      departmentName: [],
      roomName: [],
      dataTree: [],
      cardState:-1
    }
  },
  created() {
    this.changeschoolid = this.$store.state.user.changeschoolid
    this.administrator = sessionStorage.getItem('administrator')
  },
  mounted() {
    this.getDeptTree()
    this.getDataTree()
    this.loadCol()
  },
  methods: {
    // 缓存的初次加载列
    loadCol() {
      if (localStorage.getItem('customUser')) {
        let tempThead = JSON.parse(JSON.stringify(this.formThead))
        //自定义用户列已经编辑过
        // console.log(localStorage.getItem('customUser'));
        let arr = Object.keys(this.formThead)
        let arr1 = Object.keys(JSON.parse(localStorage.getItem('customUser')))
        if (JSON.stringify(arr) == JSON.stringify(arr1)) {
          this.formThead = JSON.parse(localStorage.getItem('customUser'))
        } else {
          console.log('失败')
          this.formThead = tempThead
        }
      }
    },
    //多选框修改事件
    checkboxChanged() {
      //保存用户自定义列
      localStorage.setItem('customUser', JSON.stringify(this.formThead))
      this.$nextTick(() => {
        this.$refs['tableData'].doLayout()
      })
    },
    //挂失解挂
    cardLoss(row, optionState) {
      let msg
      if (optionState == 1) {
        msg = '是否挂失该卡?'
      } else {
        msg = '是否解除该卡挂失?'
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.cardLossCommit(row, optionState)
        })
        .catch(() => {})
    },
    cardLossCommit(row, optionState) {
      // optionState : 1挂失 其他解挂
      let msg, dateTime
      if (optionState == 1) {
        msg = '挂失成功'
      } else {
        msg = '解挂成功'
      }
      dateTime = this.getimeto('YYYY-mm-dd HH:MM:SS')
      this.$http({
        url: this.$http.adornUrl('/api/v1/Student/lossCard'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            cardNumber: row.cardNumber,
            isDelete: 0,
            logicalCardNumber: '',
            lossTime: dateTime,
            state: optionState,
            operatorGuid: this.administrator,
            unitGuid: this.changeschoolid,
            userGuid: row.userGuid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.$message({
            message: msg,
            type: 'success'
          })
          this.initpage()
        } else {
          this.$message.error(data.errorMessage)
          return
        }
      })
    },

    //递归增加各节点name，并且删除type为'room'的children
    recursiveRoom(dataTree) {
      for (var i in dataTree) {
        dataTree[i].value = dataTree[i].name
        if (dataTree[i].type == 'room') {
          delete dataTree[i].children
        }
        if (dataTree[i].children) {
          this.recursiveRoom(dataTree[i].children)
        }
      }
    },
    //获取区域楼栋房间树信息
    getDataTree() {
      this.$http({
        url: this.$http.adornUrl('/area/room/get-area-room-tree'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid,
            userGuid: this.administrator
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode === 200) {
          this.dataTree = data.messageContent
          this.recursiveRoom(this.dataTree)
          // console.log(JSON.stringify(this.dataTree));
        }
      })
    },
    // 条件查询用户信息
    gotosearch() {
      this.initpage()
    },
    //重置查询条件
    resetfilter() {
      this.userName = ''
      this.userNumber = ''
      this.cardNumber = ''
    },

    // 部门树节点点击
    handleNodeClick(data) {
      this.departmentGuid = data.departmentGuid
      this.departmentName = data.departmentName
      this.pageNum = 1
      this.initpage()
    },

    // 部门树
    getDeptTree() {
      this.$http({
        url: this.$http.adornUrl('/department/select-department-tree'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: this.changeschoolid,
          messageType: 0
        })
      }).then(({ data }) => {
        // console.log(data.messageContent);
        if (data.messageCode == 200) {
          this.deptTree = data.messageContent
          this.recursiveget(this.deptTree)
          // this.idArr = []
          // this.getId(this.deptTree)
          // console.log(JSON.stringify(this.deptTree));
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    //递归添加
    recursiveget(deptTree) {
      for (var i in deptTree) {
        deptTree[i].value = deptTree[i].departmentGuid
        deptTree[i].label = deptTree[i].departmentName
        if (deptTree[i].children.length == 0) {
          delete deptTree[i].children
        } else {
          this.recursiveget(deptTree[i].children)
        }
      }
    },
    //获取递归id
    getId(deptTree) {
      deptTree.forEach(ele => {
        if (ele.flag == true) {
          this.idArr.push(ele.id)
          if (ele.children && ele.children.length > 0) {
            this.getId(ele.children)
          }
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.initpage()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.initpage()
    },
    // 初始化人事资料页面
    initpage() {
      // 终止上一次请求
      if (typeof this.cancel === 'function') {
        this.cancel()
      }
      // 取消请求函数
      let CancelToken = axios.CancelToken
      this.$http({
        url: this.$http.adornUrl('/api/v1/Student/user-department-card-page'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            asc: true,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: {
              departmentGuid: this.departmentGuid,
              unitGuid: this.changeschoolid,
              cardNumber: this.cardNumber,
              userName: this.userName,
              userNumber: this.userNumber,
              cardState:this.cardState
            },
            sortName: this.sortName
          },
          messageType: 0
        }),
        // 取消请求对象// 这个参数 c 就是CancelToken构造函数里面自带的取消请求的函数，这里把该函数当参数用 })
        cancelToken: new CancelToken(c => {
          this.cancel = c
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.tableData = data.messageContent.data
          this.recordCount = data.messageContent.recordCount
          this.currentPage = data.messageContent.pageNum
          this.tableData.forEach(item => {
            if (item.userSex === 0) {
              this.$set(item, 'userSexStr', '男')
            } else {
              this.$set(item, 'userSexStr', '女')
            }
          })
          // console.log(this.tableData);
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    }
  },
  filters: {
    filtersex: function(sex) {
      if (sex == '0') {
        return '男'
      } else if (sex == '1') {
        return '女'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-radio{
  margin-right: 0px;
}
.el-radio+.el-radio{
  margin-left: 10px;
}
.user-info {
  /deep/.el-dialog--center .el-dialog__body {
    padding-top: 0;
  }
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }
  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }
  .all_main {
    height: 100%;
    .header_title {
      padding: 20px 0;
      font-weight: bolder;
      text-align: left;
      border-bottom: 1px solid #e5e9f2;
      color: #909399;
    }
    .all_left {
      height: 100%;
      .bg-purple {
        height: 100%;
      
        .header_title {
          padding: 20px 0;
          font-weight: bolder;
          text-align: center;
          border-bottom: 1px solid #e5e9f2;
          color: #909399;
          overflow: hidden;
        }
        .department_tree {
          // width: 250px;
          height: calc(100vh - 200px);
          overflow-y: auto;
          &::-webkit-scrollbar {
            width: 0;
            height: 0;
            background-color: transparent;
          }
          padding-top: 10px;
          font-weight: bolder;
          .custom-tree-node {
            padding-left: 10px;
            font-size: 15px;
            .colorfont {
              color: DeepSkyBlue;
            }
          }
        }
      }
    }
    .all_right {
      /deep/.el-button + .el-button {
        margin: 0 6px;
      }
      .el-table__body-wrapper .is-scrolling-left {
        height: 500px;
      }
      height: calc(100vh - 140px);
      overflow: auto;
      &::-webkit-scrollbar {
        width: 0;
        height: 0;
        background-color: transparent;
      }
      .bg-purple {
        height: 100%;
        .header_title {
          padding: 10px 0 20px 0;
          font-weight: bolder;
          text-align: center;
          border-bottom: 1px solid #e5e9f2;
          color: #909399;
        }
        .el-table th {
          height: 100%;
          display: table-cell !important;
        }
        .page {
          padding-bottom: 10px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .form{
          padding-top: 10px;
        }
        /deep/.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
          margin-bottom: 5px;
        }
       
      }
    }
  }
}
.grid-content.bg-purple.aa {
  margin-left: -85px !important;
}
</style>